<template>
  <div class="register-container">
    <el-card class="register-card">
      <template #header>
        <div class="card-header">
          <h2>用户注册</h2>
        </div>
      </template>

      <el-form
        ref="registerFormRef"
        :model="registerForm"
        :rules="rules"
        label-width="80px"
        status-icon
      >
        <el-form-item label="用户名" prop="username">
          <el-input
            v-model="registerForm.username"
            placeholder="请输入用户名（4-20个字符）"
            prefix-icon="User"
          ></el-input>
        </el-form-item>

        <el-form-item label="密码" prop="password">
          <el-input
            v-model="registerForm.password"
            type="password"
            placeholder="请输入密码（6-20个字符）"
            prefix-icon="Lock"
            show-password
          ></el-input>
        </el-form-item>

        <el-form-item label="确认密码" prop="confirmPassword">
          <el-input
            v-model="registerForm.confirmPassword"
            type="password"
            placeholder="请再次输入密码"
            prefix-icon="Lock"
            show-password
          ></el-input>
        </el-form-item>

        <!-- <el-form-item label="邮箱" prop="email">
          <el-input 
            v-model="registerForm.email" 
            placeholder="请输入邮箱"
            prefix-icon="Message"
          ></el-input>
        </el-form-item> -->

        <!-- <el-form-item label="验证码" prop="captcha">
          <div class="captcha-container">
            <el-input 
              v-model="registerForm.captcha" 
              placeholder="请输入验证码"
            ></el-input>
            <el-button 
              type="primary" 
              :disabled="captchaDisabled" 
              @click="sendCaptcha"
            >
              {{ captchaText }}
            </el-button>
          </div>
        </el-form-item> -->

        <el-form-item>
          <el-checkbox v-model="registerForm.agreement">
            我已阅读并同意
            <el-link type="primary" @click="showAgreement"
              >《用户协议》</el-link
            >
          </el-checkbox>
        </el-form-item>

        <el-form-item>
          <el-button
            type="primary"
            @click="submitRegister"
            :loading="submitting"
            :disabled="!registerForm.agreement"
          >
            注册
          </el-button>
          <el-button @click="goToLogin">已有账号，去登录</el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script setup>
import { ref, reactive } from "vue";
import { useRouter } from "vue-router";
import { ElMessage, ElMessageBox } from "element-plus";
import { User, Lock, Message } from "@element-plus/icons-vue";

const router = useRouter();
const registerFormRef = ref(null);
const submitting = ref(false);

// 注册表单数据
const registerForm = reactive({
  username: "",
  password: "",
  confirmPassword: "",
  email: "",
  captcha: "",
  agreement: false,
});

// 验证码按钮状态
const captchaDisabled = ref(false);
const captchaText = ref("获取验证码");
const captchaTimer = ref(null);

// 表单验证规则
const validatePass = (rule, value, callback) => {
  if (value === "") {
    callback(new Error("请输入密码"));
  } else {
    if (registerForm.confirmPassword !== "") {
      registerFormRef.value.validateField("confirmPassword");
    }
    callback();
  }
};

const validatePass2 = (rule, value, callback) => {
  if (value === "") {
    callback(new Error("请再次输入密码"));
  } else if (value !== registerForm.password) {
    callback(new Error("两次输入密码不一致"));
  } else {
    callback();
  }
};

const rules = {
  username: [
    { required: true, message: "请输入用户名", trigger: "blur" },
    { min: 4, max: 20, message: "长度在 4 到 20 个字符", trigger: "blur" },
  ],
  password: [
    { required: true, message: "请输入密码", trigger: "blur" },
    { min: 6, max: 20, message: "长度在 6 到 20 个字符", trigger: "blur" },
    { validator: validatePass, trigger: "blur" },
  ],
  confirmPassword: [
    { required: true, message: "请再次输入密码", trigger: "blur" },
    { validator: validatePass2, trigger: "blur" },
  ],
  email: [
    { required: true, message: "请输入邮箱地址", trigger: "blur" },
    { type: "email", message: "请输入正确的邮箱地址", trigger: "blur" },
  ],
  captcha: [
    { required: true, message: "请输入验证码", trigger: "blur" },
    { len: 6, message: "验证码长度为6位", trigger: "blur" },
  ],
};

// 发送验证码
const sendCaptcha = () => {
  if (!registerForm.email) {
    ElMessage.warning("请先输入邮箱地址");
    return;
  }

  // 验证邮箱格式
  const emailReg = /^[a-zA-Z0-9_-]+@[a-zA-Z0-9_-]+(\.[a-zA-Z0-9_-]+)+$/;
  if (!emailReg.test(registerForm.email)) {
    ElMessage.warning("请输入正确的邮箱地址");
    return;
  }

  captchaDisabled.value = true;
  let countdown = 60;
  captchaText.value = `${countdown}秒后重新获取`;

  // 模拟发送验证码
  ElMessage.success(`验证码已发送至邮箱: ${registerForm.email}`);

  // 实际API调用应该类似：
  // await request.post('/api/auth/captcha', { email: registerForm.email });

  captchaTimer.value = setInterval(() => {
    countdown--;
    captchaText.value = `${countdown}秒后重新获取`;
    if (countdown <= 0) {
      clearInterval(captchaTimer.value);
      captchaDisabled.value = false;
      captchaText.value = "获取验证码";
    }
  }, 1000);
};

// 提交注册
const submitRegister = () => {
  if (!registerFormRef.value) return;

  registerFormRef.value.validate(async (valid) => {
    if (!valid) {
      ElMessage.warning("请完善表单信息");
      return;
    }

    if (!registerForm.agreement) {
      ElMessage.warning("请阅读并同意用户协议");
      return;
    }

    submitting.value = true;
    try {
      // 模拟API调用
      setTimeout(() => {
        ElMessage.success("注册成功，请登录");
        router.push("/login");
        submitting.value = false;
      }, 1000);

      // 实际API调用应该类似：
      // await request.post('/api/auth/register', {
      //   username: registerForm.username,
      //   password: registerForm.password,
      //   email: registerForm.email,
      //   captcha: registerForm.captcha
      // });
    } catch (error) {
      console.error("注册失败:", error);
      ElMessage.error("注册失败，请稍后重试");
      submitting.value = false;
    }
  });
};

// 显示用户协议
const showAgreement = () => {
  ElMessageBox.alert(
    `
    1. 用户在注册时应当提供真实、准确、完整的个人资料。
    2. 用户应当对账号安全负责，不得将账号借给他人使用。
    3. 用户在使用本平台服务时应遵守相关法律法规。
    4. 用户不得发布违法、色情、暴力等不良信息。
    5. 平台有权对违反协议的用户采取限制措施。
    6. 平台会保护用户的个人隐私信息。
    `,
    "用户协议",
    {
      confirmButtonText: "我已阅读",
      callback: () => {
        registerForm.agreement = true;
      },
    }
  );
};

// 跳转到登录页
const goToLogin = () => {
  router.push("/login");
};
</script>

<style scoped>
.register-container {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100vh;
  background-color: #f8f9fa;
}

.register-card {
  width: 450px;
}

.card-header {
  text-align: center;
}

.captcha-container {
  display: flex;
  gap: 10px;
}

.captcha-container .el-input {
  flex: 1;
}

.captcha-container .el-button {
  width: 120px;
}
</style>
